package server;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 类加载器
 */
public class MyClassLoader extends ClassLoader {

    //等于项目的根目录下的webapps目录  F:\studyProject\Minicat\webapps
    private String loadrootpath;
    //具体项目的文件名名称 demo1 demo2
    private String webcontext;

    public MyClassLoader(String loadrootpath, String webcontext) {
        this.loadrootpath = loadrootpath;
        this.webcontext = webcontext;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classbytes = null;
            classbytes = loadclassbytes(name);
            //定义类向JVM输入字节码文件
            Class<?> aClass = defineClass(name, classbytes, 0, classbytes.length);
            return aClass;
        } catch (IOException e) {
            throw new ClassNotFoundException(name);
        }
    }

    private byte[] loadclassbytes(String name) throws IOException {
        String contextpath = loadrootpath + "\\" + webcontext;

        name = contextpath +  "\\" + name.replace(".", "\\");

        String cname = name + ".class";//获取字节码文件名

        byte[] bytes = Files.readAllBytes(Paths.get(cname));
        return bytes;

    }
}


